package com.jwkj.collector.modbus.codec.impl;


import com.jwkj.collector.modbus.base.ModbusDataGram;
import com.jwkj.collector.modbus.codec.ModbusRTUDecoder;
import com.jwkj.collector.modbus.codec.ModbusRTUEncoder;
import com.jwkj.collector.modbus.request.MultiReadRequest;
import com.jwkj.collector.modbus.request.MultiWriteRequest;
import com.jwkj.collector.modbus.request.OneWriteRequest;
import com.jwkj.collector.modbus.response.MultiReadResponse;
import com.jwkj.collector.modbus.response.MultiWriteResponse;
import com.jwkj.collector.modbus.response.OneWriteResponse;

/**
 * 统一编码解码器
 * 
 * @author lixiaolong
 * @CreateDate 2018年3月19日
 */
public class ModbusRTUCodec implements ModbusRTUDecoder<ModbusDataGram>, ModbusRTUEncoder<ModbusDataGram> {

	private ModbusRTUCodec() {

	}

	/**
	 * 获取实例
	 * 
	 * @Author lixiaolong
	 * @CreateDate
	 * @return
	 */
	public static ModbusRTUCodec getInstance() {
		return new ModbusRTUCodec();
	}

	@Override
	public byte[] encode(ModbusDataGram data) {
		return data.toBytes();
	}

	@Override
	public ModbusDataGram decodeTx(byte[] buf) {
		byte funCode = buf[1];
		switch (funCode) {
		case 0x03: {
			return new MultiReadRequest(buf);
		}
		case 0x05: {
			return new OneWriteRequest(buf);
		}
		case 0x10: {
			return new MultiWriteRequest(buf);
		}
		default: {
			throw new RuntimeException("该功能码[" + funCode + "]不存在");
		}
		}
	}

	@Override
	public ModbusDataGram decodeRx(byte[] buf) {
		byte funCode = buf[1];
		switch (funCode) {
		case 0x03: {
			return new MultiReadResponse(buf);
		}
		case 0x05: {
			return new OneWriteResponse(buf);
		}
		case 0x10: {
			return new MultiWriteResponse(buf);
		}
		default: {
			throw new RuntimeException("该功能码[" + funCode + "]不存在");
		}
		}
	}

}
